<?php
require_once('Zend/Auth/Adapter/DbTable.php');
require_once('Zend/Auth.php');

class Third_Auth
{
	private $_table = 'usuarios';
	private $_session;
	private $__auth;
	private $_acl;

	// Zend_Auth Adapter fields
	private $_timeToExpire = 900; //in seconds
	private $_db;

	public function __construct( )
	{
		$this->_db = Zend_Registry::get('db');
		$this->_table = $this->_table;
		
		$this->_auth  = new Zend_Auth_Adapter_DbTable( $this->_db );
		
	    // INACTIVITY Sign Out
	    $inactivity = new Zend_Session_Namespace('Inactivity');
	    if ((isset($inactivity->lastActivity) === true) AND ((time()-$inactivity->lastActivity) > $this->_timeToExpire )) {
	            Zend_Auth::getInstance()->clearIdentity();
	    }

	    $inactivity->lastActivity = time();
	}

	public function authenticate( $username, $password ){

		$this->_auth->setTableName( $this->_table );
		$this->_auth->setIdentityColumn( 'login');
		$this->_auth->setCredentialColumn( 'senha' );

		$this->_auth->setIdentity( strtolower( $username ) );
		$this->_auth->setCredential( strtolower( md5( $password ) ) );

		$auth = Zend_Auth::getInstance();

		$result = $auth->authenticate( $this->_auth );

		if ($result->isValid())
		{
			$data = $this->_auth->getResultRowObject(null, 'senha');
			
			$user = Third_Funcs::toArray( $data );

			require_once( "Usuarios.php" );
			$usuarios = new Usuarios();

			$auth->getStorage()->write( $data );
		} else {
			$data = false;
		}

		return $data;
	}

	public function logout(){
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
		$auth->getStorage()->write( NULL );

		return $auth->getStorage()->clear();
	}

	public function getLogged(){
		$auth = Zend_Auth::getInstance();

		return $auth->getStorage()->read();
	}
	
	public function getLoggedId(){
		$auth = Zend_Auth::getInstance();
		$data = $auth->getStorage()->read();

		if( $data )
			return $data->id;
		else
			return 0;
	}
	
	public function isLogged(){
		$auth = Zend_Auth::getInstance();

		if( $auth->hasIdentity() )
			return true;

		return false;
	}

	public function isUserLoggedVerify(){
		if( ! $this->getLogged() ){
			header( 'location: /users/login' );
		}
	}
	
	public function update( $data ){
		$auth = Zend_Auth::getInstance();
		
		$infos = Third_Funcs::toArray( $this->getLogged() );

		foreach( $data as $key=>$value ){
			$infos[ $key ] = $value;
		}
		
		require_once( "Usuarios.php" );
		$user = ProfilesModel::formatUserData( $infos );
		
		$auth->getStorage()->write( $user );
	}

	public function setSession( $session ){
		$this->_session = $session;
	}
}
